<?php


namespace App\Libraries\VerifyPhoneNumber;


use Illuminate\Support\Facades\Cache;

class Verifier
{
    const VERIFICATION_KEY = 'sms.verification.%s';

    protected $ttl = 600;

    public function setTtl(int $ttl)
    {
        $this->ttl = $ttl;

        return $this;
    }

    protected function getCode()
    {
        return mt_rand(100000, 999999);
    }

    /**
     * @param string $phoneNumber
     * @return int
     */
    public function new(string $phoneNumber)
    {
        $code = $this->getCode();

        $index = sprintf(self::VERIFICATION_KEY, $phoneNumber);
        Cache::forget($index);
        Cache::put($index, $code, $this->ttl);

        return $code;
    }

    /**
     * 检查验证码是否匹配.
     *
     * @param string $key
     * @param int $code
     * @return bool
     */
    public function match(string $key, int $code)
    {
        $key = sprintf(self::VERIFICATION_KEY, $key);
        $storedCode = Cache::get($key);

        if ($storedCode === $code) {
            Cache::forget($key);

            return true;
        }

        return false;
    }
}
